package com.xiaoy.core.basic.organization.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaoy.core.basic.organization.entity.Organization;
import com.xiaoy.core.basic.organization.entity.Party;
import com.xiaoy.core.basic.organization.entity.PartyType;
import com.xiaoy.dao.DaoUtil;
import com.xiaoy.exception.SystemException;
import com.xiaoy.util.store.config.ConfigTable;

@Service("organizationService")
public class OrganizationService {
	
	private String tablename = ConfigTable.Basic.ORGANIZATION+" t ";
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Resource(name="partyTypeSerivce")
	private PartyTypeSerivce partyTypeSerivce;
	
	@Resource(name="daoUtil")
	private DaoUtil<Organization, Long>daoUtil;
	@Transactional
	public List<Organization> getAll() {
		
		return null;
	}
	
	/**
	 * 得到组织机构的树根
	 * @return
	 */
	public List<Organization>getOrgRoot (){
		
		String sql = "select * from "+tablename +" order by typeid, pid desc ";//+" where (pid is null or pid = 0)";
		List<Organization>orgs = daoUtil.query(Organization.class, sql);
		return createOrgTree(orgs);
	}
	
	/**
	 * 得到类型的下的所有的机构
	 * @param typeid
	 * @return
	 */
	@Transactional
	public List<Organization> getByTypeid(String typeid) {
		
		String sql = "select * from "+tablename +" where t.typeid='"+typeid+"'";
//		SQLQuery query = daoUtil.getSession().createSQLQuery(sql);
		List<Organization>orgs = daoUtil.query(Organization.class, sql);
		return orgs;
	}
	
	@Transactional
	public Organization getById (long id) {
		
		return (Organization)daoUtil.getSession().get(Organization.class,id);
	}
	
	/**
	 * 得到这个机构类型下所有的父机构
	 * @param typeid
	 * @return
	 */
	@Transactional
	public List<Organization> getParentOrgByTypeid(String typeid){
		
		String sql = "select * from "+tablename +" where t.typeid<='"+typeid+"' order by typeid ";
		List<Organization>orgs = daoUtil.query(Organization.class, sql);
		return orgs;
	}
	
	@Transactional
	public List<Organization> getParentOrgWithTreeByTypeid(String typeid){
		String sql = "select * from "+tablename +" where t.typeid<='"+typeid+"' order by typeid, pid desc ";
		List<Organization>orgs = daoUtil.query(Organization.class, sql);
		
		return  createOrgTree(orgs);
	}
	//--------生成组织结构的树-----------start
	/**
	 * 生成组织结构的树
	 * @param temps
	 * @return
	 */
	private List<Organization> createOrgTree (List<Organization>temps) {
		List<Organization>result = new ArrayList<Organization>();
		for (int i=0;i<temps.size();i++) {
			
			Organization temp = temps.get(i);
			result.add(temp);
			temps.remove(i);
			i--;
			createOrgTreeNode(temps,temp);
		}
		return result;
	}
	
	/**
	 * 生成组织结构的树节点
	 * @param orgs
	 * @param current
	 */
	private void createOrgTreeNode (List<Organization> orgs,Organization current){
		List<Party>children = new ArrayList<Party>();
		for (int j=0;j<orgs.size();j++) {
			Organization o = orgs.get(j);
			
			if (o.getParent()!=null&&o.getParent().getId()==current.getId()) {
				children.add(o);
				orgs.remove(j);
				j--;
				createOrgTreeNode(orgs,o);
			}
		}
		current.setChildren(children);
	}
	//--------生成组织结构的树-----------end;
	
	@Transactional
	public void saveOrUpdate (Organization org) throws SystemException{
		try{
			daoUtil.saveOrUpdate(org);
		}catch (Exception e) {
			logger.error("保存组织结构错误",e);
			throw new SystemException("保存组织结构错误!");
		}
		
	}
	
	
	@Transactional
	public void saveOrUpdate (Organization org,long typeid,long parentid) throws SystemException{
		try{
			PartyType type = partyTypeSerivce.getById(typeid);
			Organization parent = getById(parentid);
	//		System.err.println("parent.getName()-->"+parent.getName()+"       type.getName()-->"+type.getName());
			org.setPartyType(type);
			org.setParent(parent);
			saveOrUpdate(org);
		}catch (Exception e) {
			logger.error("保存组织结构错误",e);
			throw new SystemException("保存组织结构错误!");
		}
	}
}
